package com.zx.common;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.io.FileUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


/**
 * @Project: 20170714_restClient
 * @Title: HttpUtils2
 * @Description: HttpUtils工具类的优化版
 * @author: zhangxue
 * @date: 2017年7月15日上午9:51:17
 * @company: webyun
 * @Copyright: Copyright (c) 2017
 * @version v1.0
 */
public class HttpUtils {

	private static final String REQUEST_HEADER = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102";
	
	public static void main(String[] args) {
		
		Map<String, String> params = new HashMap<>();// 请求的参数
		params.put("jl", "北京");
		params.put("kw", "大数据");
		
		String string = get("http://sou.zhaopin.com/jobs/searchresult.ashx", params);
		System.out.println(string);
		// url
//		String url = "http://localhost:8080/20170714_restClient/user.do";
//		Map<String, String> params = new HashMap<>();// 请求的参数
//		params.put("name", "测试参数");
//		String post = post(url, params);// 访问URL，并获得结果
//		System.out.println("获得结果" + post);
//		User user = JsonUtils.jsonToObject(post, User.class);// 将结果转换为对象
//		System.out.println(user);
		
		
		downlond("http://static.runoob.com/images/icon/html.png", "image");
		
	}
	
	/**
	 * 简单post请求，获得全部的response
	 * @param postUrl
	 * @param args
	 * @return
	 */
    public static String post(String postUrl, Map<String, String> args){
        if(postUrl == null || postUrl.length() == 0)
            return null;
        
    	//获得响应
    	HttpHandler httpHandler = postMethod(postUrl, args);
    	
    	CloseableHttpResponse response = httpHandler.getResponse();
    	CloseableHttpClient httpClient = httpHandler.getHttpClient();
    	
		//	2.获得返回集		
		try {
			// 判断响应码
			boolean ok = isOk(response);
			
        	if(ok){//正常响应,获得响应文
        		return getResponseContext(response, null);
        	} 
		} catch (Exception e) {//解析异常
			e.printStackTrace();
		} finally {
			close(response, httpClient);
		}
		return null;
    }
    
    /**
     * 简单get请求，获得全部的response
     * @param getUrl
     * @param args
     * @return
     * @author: zhangxue
     * @date: 2017年7月15日上午9:52:37
     * @version v1.0
     */
    public static String get(String getUrl, Map<String, String> args) {
    	if(getUrl == null || getUrl.length() == 0)
            return null;
    	//获得响应
    	HttpHandler httpHandler = getMethod(getUrl, args);
    	
    	CloseableHttpResponse response = httpHandler.getResponse();
    	CloseableHttpClient httpClient = httpHandler.getHttpClient();
    	
		//	2.获得返回集		
		try {
			// 判断响应码
			boolean ok = isOk(response);
			
        	if(ok){//正常响应,获得响应文
        		return getResponseContext(response, null);
        	} 
		} catch (Exception e) {//解析异常
			e.printStackTrace();
		} finally {
			close(response, httpClient);
		}
		return null;
	}
    
    /**
     * 文件下载
     * @param getUrl
     * @param fileType	文件的类型，如image
     * @author: zhangxue
     * @date: 2017年7月15日上午10:08:31
     * @version v1.0
     */
    public static void downlond(String getUrl, String fileType) {
    	if(getUrl == null || getUrl.length() == 0)
            return;
    	
    	//获得响应
    	HttpHandler httpHandler = getMethod(getUrl, null);
    	
    	CloseableHttpResponse response = httpHandler.getResponse();
    	CloseableHttpClient httpClient = httpHandler.getHttpClient();
    	
		//	2.获得返回集		
		try {
			// 判断响应码
			boolean ok = isOk(response);
        	if(ok){//正常响应
        		HttpEntity entity = response.getEntity();//获得响应主体
        		//获得content-type(返回结果的类型，[编码]),image/jpeg
        		String contentType = entity.getContentType().getValue();
        		//判断是否为图片
        		boolean b = contentType.contains(fileType);
        		
        		if(b){
        			//获得输入流
        			InputStream is = entity.getContent();
        			FileUtils.copyInputStreamToFile(is, new File("d://测试1.png"));
        		}
        	} 
		} catch (ParseException e) {//解析异常
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			close(response, httpClient);
		}
		return;
	}
    
    
    /* ******************************以下为内部工具类***********************************************/
    /**
     * 获得get响应
     * @param getUrl
     * @param args
     * @return
     * @author: zhangxue
     * @date: 2017年7月15日上午10:54:44
     * @version v1.0
     */
    private static HttpHandler getMethod(String getUrl, Map<String, String> args){
    	CloseableHttpClient httpClient = HttpClients.createDefault();
		
		if(args != null && args.size() != 0){
			StringBuffer params = new StringBuffer("?");
			for (Entry<String, String> nameValuePair : args.entrySet()) {
				params.append(nameValuePair.getKey()).append("=").append(nameValuePair.getValue()).append("&");
			}
			getUrl += params.toString();
		}
		
		HttpGet httpGet = new HttpGet(getUrl);
		
		//模拟浏览器
		httpGet.setHeader("User-Agent", REQUEST_HEADER);
		CloseableHttpResponse response = null;
		
		try {
			//创建请求的配置对象
        	Builder builder = RequestConfig.custom();
        	builder.setConnectTimeout(50 * 1000);//设置请求的超时时间
        	httpGet.setConfig(builder.build());
        	
			//获得响应
			response = httpClient.execute(httpGet);
			
			HttpHandler handler = new HttpHandler();
			handler.setHttpClient(httpClient);
			handler.setResponse(response);
			
			return handler;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
    }
    
    /**
     * 获得post响应
     * @param postUrl
     * @param args
     * @return
     * @author: zhangxue
     * @date: 2017年7月15日上午10:54:31
     * @version v1.0
     */
    private static HttpHandler postMethod(String postUrl, Map<String, String> args){
    	CloseableHttpClient httpClient = HttpClients.createDefault();
		
    	HttpPost httpPost = new HttpPost(postUrl);
        
        //设置参数
        List<NameValuePair> params = new ArrayList<>();
        for (Entry<String, String> nameValuePair : args.entrySet()) {
        	params.add(new BasicNameValuePair(nameValuePair.getKey(), nameValuePair.getValue()));
		}
        
        //转换参数并设置编码格式  
        httpPost.setEntity(new UrlEncodedFormEntity(params,Consts.UTF_8)); 
		
		//模拟浏览器
        httpPost.setHeader("User-Agent", REQUEST_HEADER);
		CloseableHttpResponse response = null;
		
		try {
			//创建请求的配置对象
        	Builder builder = RequestConfig.custom();
        	builder.setConnectTimeout(50 * 1000);//设置请求的超时时间
        	httpPost.setConfig(builder.build());
        	
			//获得响应
			response = httpClient.execute(httpPost);
			
			HttpHandler handler = new HttpHandler();
			handler.setHttpClient(httpClient);
			handler.setResponse(response);
			
			return handler;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
    }
    
    /**
     * 获得响应的正文--以字符串的形式
     * @param response
     * @return
     * @author: zhangxue
     * @date: 2017年7月15日上午10:39:03
     * @version v1.0
     */
    private static String getResponseContext(CloseableHttpResponse response, String charset){
    	HttpEntity entity = response.getEntity();
		String contentType = entity.getContentType().getValue();
		
		if(charset == null) {
			boolean contains = contentType.toLowerCase().contains("charset");
			if(contains) {//响应中说明编码
				charset = contentType.substring(contentType.indexOf("charset=") + 8);
			}
		}
		String html = null;
		try {
			html = EntityUtils.toString(entity, charset);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}//设置编写
		return html;
		
    }
    
    /**
     * 响应码是否是200
     * @param response
     * @return
     * @author: zhangxue
     * @date: 2017年7月15日上午10:47:57
     * @version v1.0
     */
    private static boolean isOk(CloseableHttpResponse response){
    	return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
    }
    
    /**
     * 关闭资源
     */
    private static void close(CloseableHttpResponse response, CloseableHttpClient httpClient){
		try {
			response.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			httpClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    /**
     * httpclient模型
     * @Project: 20170714_restClient
     * @Title: HttpHandler
     * @Description: TODO
     * @author: zhangxue
     * @date: 2017年7月15日上午10:54:14
     * @company: webyun
     * @Copyright: Copyright (c) 2017
     * @version v1.0
     */
    private static class HttpHandler {
	
    	private CloseableHttpResponse response;
    	
    	private CloseableHttpClient httpClient;
    	
		public CloseableHttpResponse getResponse() {
			return response;
		}

		public void setResponse(CloseableHttpResponse response) {
			this.response = response;
		}

		public CloseableHttpClient getHttpClient() {
			return httpClient;
		}

		public void setHttpClient(CloseableHttpClient httpClient) {
			this.httpClient = httpClient;
		}
    }
    
}
